package com.example.hao.broadcastreceiver_service;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;


/**
 * Activity 与 Service 的交互
 * <p>
 * BroadcastReceiver   (原始交互方式一)
 * 使用 BindService      (原始的交互方式二)
 * 使用 Application 全部对象 (不要用)
 * RxJava 响应式编程
 * EventBus /MessageBus 事件巴士 (第三方Api  推荐)
 */

public class MainActivity2 extends AppCompatActivity implements ServiceConnection {


    public interface MusicProgressCallback {
        void onProgress(int progress);

        void onComplete();
    }


    private String TAG = MainActivity2.class.getSimpleName();
    private TextView tv_show;
    private SeekBar sb;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        sb = findViewById(R.id.sb);
        tv_show = findViewById(R.id.tv_show);
        startService(new Intent(this, MyService2.class));
    }


    public void unBind(View view) {
        unbindService(this);
    }

    public void bind(View view) {
        Intent intent = new Intent(this, MyService2.class);
        bindService(intent, this, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    public void play(View view) {
        myBinder.a("啊哈哈哈");
    }


    public void pause(View view) {
        myBinder.b();
    }

    public void next(View view) {
        myBinder.c();
    }

    private MyService2.MyBinder myBinder;

    /**
     * 服务绑定成功,该方法被调用
     *
     * @param name
     * @param service 服务的 onBind方法的返回值对象
     */
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.i(TAG, "onServiceConnected: " + service);
        if (service instanceof MyService2.MyBinder) {
            myBinder = (MyService2.MyBinder) service;
            myBinder.setMusicProgressCallback(new MusicProgressCallback() {
                @Override
                public void onProgress(int progress) {
                    sb.setProgress(progress);
                    tv_show.setText(progress + "%");
                }

                @Override
                public void onComplete() {

                }
            });
        }

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
}
